package ar.edu.itba.infovis.TPF;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ar.edu.itba.infovis.TPF.twitter.TwitterStream;

public class MainServlet extends HttpServlet {

	private static final long serialVersionUID = 5236786874126365727L;

	public static int MAXSUBJECTS = 5;
	public static int MINSUBJECTS = 1;
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		List<String> subjects = new ArrayList<String>(MainServlet.MAXSUBJECTS);
		for(int i=0;i<MainServlet.MAXSUBJECTS;++i) {
			String subject = req.getParameter("subject"+(i+1));
			if(subject!=null && !subject.isEmpty()) {
				subjects.add(subject.toLowerCase());
				req.setAttribute("subject" + (i+1), subject.toLowerCase());
			}
		}
		
		if(subjects.size()<MainServlet.MINSUBJECTS) {
			RequestDispatcher dispatcher = req.getRequestDispatcher("/edit.jsp");
			req.setAttribute("error", 1);
			dispatcher.forward(req, resp);
		}
		else {
			TwitterStream stream = TwitterStream.getInstance();
			stream.stream(subjects, true);
			RequestDispatcher dispatcher = req.getRequestDispatcher("/view.jsp");
			req.setAttribute("subjects", subjects);
			dispatcher.forward(req, resp);
		}
	}
	
}